package org.footito.android.ui.views;

import org.footito.android.R;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

public class CounterView extends FrameLayout {
	private int counter = 1;
	private TextView tv;
	private ImageView iv;
	private final Runnable action = new Runnable() {
		@Override
		public void run() {
			displayCount();
		}
	};

	public CounterView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		createView(context);
		displayCount();
	}

	public CounterView(Context context, AttributeSet attrs) {
		super(context, attrs);
		createView(context);
		displayCount();
	}

	public CounterView(Context context) {
		super(context);
		createView(context);
		displayCount();
	}

	private void createView(Context context) {
		LayoutInflater.from(context).inflate(R.layout.counter_view, this);
		tv = (TextView) findViewById(R.id.TextViewCount);
		iv = (ImageView) findViewById(R.id.ImageViewCount);
	}

	public void restartCounter(Activity activity) {
		counter = 0;
		try {
			activity.runOnUiThread(action);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void displayCount() {
		if (counter == 0) {
			tv.setText("0");
			tv.setVisibility(View.GONE);
			iv.setVisibility(View.GONE);
		} else {
			tv.setVisibility(View.VISIBLE);
			iv.setVisibility(View.VISIBLE);
			if (counter < 100) {
				tv.setText("" + counter);
			} else {
				tv.setText("+");
			}
			invalidate();
		}
	}

	public void incrementCounter(Activity activity) {
		counter++;
		activity.runOnUiThread(action);

	}
	
	/**
	 * This action needs to be called in UI Thread
	 * @param value
	 */
	public void setCounter(int value){
		if (value < 0)
			return;
		counter = value;
		displayCount();
	}

	/**
	 * @param value
	 *            need to be > 0
	 */
	public void incrementCounter(Activity activity, int value) {
		if (value > 0) {
			counter += value;
			activity.runOnUiThread(action);
		}
	}

}
